package com.molichuxing.gateway.api.aspect;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;

import com.molichuxing.framework.result.ResponseCodeEnum;
import com.molichuxing.framework.result.ResponseResult;



/**
 * 参数校验AOP
 * 
 * @author zoumingyu
 *
 */
@Aspect
@Order(3)
@Component
public class BindingResultAspect {
	private final Logger logger = LoggerFactory.getLogger("[gateway参数校验日志]");

	@Pointcut("execution(public * com.molichuxing.gateway.api.services.impl..*(..))")
	public void validate() {
	}

	@Around("validate()")
	public Object doBefore(ProceedingJoinPoint joinPoint) throws Throwable {
		BindingResult bindingResult = null;
		for (Object arg : joinPoint.getArgs()) {
			if (arg instanceof BindingResult) {
				bindingResult = (BindingResult) arg;
			}
		}
		if (bindingResult != null) {
			long threadId = Thread.currentThread().getId();
			List<FieldError> errorList = bindingResult.getFieldErrors();
			if (errorList.size() > 0) {
				Map<String, Object> map = new HashMap<>();
				StringBuilder sb = new StringBuilder();
				for (FieldError fieldError : errorList) {
					map.put(fieldError.getField(), fieldError.getDefaultMessage());
					sb.append(fieldError.getDefaultMessage()+",");
				}
				logger.info("[" + threadId + "]" + joinPoint.getSignature().getDeclaringTypeName() + "."
						+ joinPoint.getSignature().getName() + ":" + map.toString());
				String message = sb.substring(0, sb.length()-1);
				return new ResponseResult<>().error(ResponseCodeEnum.PARMS_ERROR.getCode(), message);
			}
		}
		return joinPoint.proceed();
	}
}
